<template>
  <div class="app-container">
    <el-row>
      <el-col :span="5" class="card-box">
        <el-card>
          <div slot="header">
            <el-tag size="small">业务对象分类</el-tag>
            <el-button type="text" icon="el-icon-circle-close" @click="close()" style="float: right; padding: 8px; color: red">退出</el-button>
          </div>
          <div class="hi-full" style="height: 700px">
            <el-tree :data="dataTree" node-key="id" default-expand-all :expand-on-click-node="false">
              <span class="custom-tree-node" slot-scope="{ node, data }" style="width: 100%" @mouseenter="mouseenter(data)" @mouseleave="mouseleave(data)" @click="refresh">
                <span>{{ node.label }}</span>
                <span>
                  <el-button slot="reference" v-show="data.show" type="text" size="mini" icon="el-icon-plus"> </el-button>
                  <el-button slot="reference" v-show="data.show" type="text" size="mini" icon="el-icon-edit-outline"> </el-button>
                  <el-button slot="reference" v-show="data.show" type="text" size="mini" icon="el-icon-minus"> </el-button>
                </span>
              </span>
            </el-tree>
          </div>
        </el-card>
      </el-col>
      <el-col :span="19" class="card-box">
        <el-card style="height: 783px">
          <el-tabs v-model="activeName">
            <el-tab-pane label="基本信息" name="basic">
              <basic-info-form ref="basicInfo" :info="info" />
            </el-tab-pane>

            <el-tab-pane label="字段信息" name="columnInfo">
              <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                  <el-button type="primary" plain icon="el-icon-plus" size="mini" v-hasPermi="['power:dept:add']" @click="addTableInfo">新增</el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button type="success" plain icon="el-icon-edit" size="mini" @click="editTableInfo">编辑</el-button>
                </el-col>
                <!-- <el-col :span="1.5">
                  <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="deleteTableInfo">删除</el-button>
                </el-col> -->
              </el-row>

              <el-table ref="dragTable" max-height="550" :data="info.columns" v-loading="loading" row-key="columnId" border :header-cell-style="{ background: '#eef1f6', color: '#606266' }" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="40" />
                <el-table-column label="名称" prop="columnComment" :show-overflow-tooltip="true" width="220" />
                <el-table-column label="字段" prop="columnName" width="180" />
                <el-table-column label="属性类型" prop="columnType" :show-overflow-tooltip="true" width="220" />
                <el-table-column label="长度" prop="len" width="220" />
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <el-button type="text" size="small" icon="el-icon-edit" @click="editTableInfo(scope.row)" v-hasPermi="['data:business:edit']">编辑</el-button>
                    <el-button type="text" size="small" icon="el-icon-delete" @click="deleteTableInfo(scope.row)" v-hasPermi="['data:business:remove']">删除</el-button>
                    <el-button type="text" size="small" icon="el-icon-document" @click="details(scope.row)" v-hasPermi="['data:business:details']">明细</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>

          <el-form label-width="100px">
            <el-form-item style="text-align: center; margin-left: -100px; margin-top: 40px">
              <el-button type="primary" @click="submitForm()">提交</el-button>
              <el-button @click="close()">返回</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      <router-view />
    </el-row>
    <el-dialog title="添加表字段" :visible.sync="addTableInfoStatus">
      <el-form :model="tableInfoOne" :rules="rules" :disabled="disable">
        <el-form-item label="名称" prop="columnComment" :label-width="'100px'">
          <el-input v-model="tableInfoOne.columnComment" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="字段名" prop="columnName" :label-width="'100px'">
          <el-input v-model="tableInfoOne.columnName" autocomplete="off"></el-input>
        </el-form-item>

        <el-col :span="12">
          <el-form-item label="类型" prop="columnType" :label-width="'100px'">
            <el-select v-model="tableInfoOne.columnType" placeholder="请选择类型">
              <el-option label="字符串" value="varchar"></el-option>
              <el-option label="字符" value="char"></el-option>
              <el-option label="大数字" value="bigint"></el-option>
              <el-option label="数字" value="int"></el-option>
              <el-option label="日期" value="datetime"></el-option>
              <el-option label="大文本" value="text"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="长度" prop="len" :label-width="'100px'">
            <el-input-number v-model="tableInfoOne.len" controls-position="right" :min="0" :max="2000"></el-input-number>
          </el-form-item>
        </el-col>
      </el-form>

      <div slot="footer" class="dialog-footer" style="margin-left: -80px; margin-top: 70px" v-if="tableInfoOne.operation == 'add'">
        <el-button @click="addTableInfoStatus = false">取 消</el-button>
        <el-button type="primary" @click="submitFromInfoOne('add')">确 定</el-button>
      </div>
      <div slot="footer" class="dialog-footer" style="margin-left: -80px; margin-top: 70px" v-if="tableInfoOne.operation == 'change'">
        <el-button @click="addTableInfoStatus = false">取 消</el-button>
        <el-button type="primary" @click="submitFromInfoOne('change')">确 定</el-button>
      </div>
      <div slot="footer" class="dialog-footer" style="margin-left: -80px; margin-top: 70px" v-if="tableInfoOne.operation == 'details'"></div>
    </el-dialog>
  </div>
</template>
<script>
import { createSql } from '@/api/business/tableInfo'
import basicInfoForm from './basicInfoForm.vue'

import Sortable from 'sortablejs'
import IconsDialog from '../../tool/build/IconsDialog.vue'

export default {
  name: 'TableInfo',

  components: {
    basicInfoForm,
    IconsDialog
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      //树形菜单数据
      dataTree: [
        {
          id: 1,
          label: '业务对象分类表',
          show: false,
          children: []
        }
      ],
      // 显示搜索条件
      disable: false,
      // 选中选项卡的 name
      activeName: 'basic',
      // 选中数组
      ids: [],
      // 表信息
      tables: [],
      // 表列信息
      columns: [],
      // 表详细信息
      info: {
        tableName: '',
        tableComment: '',
        remark: '',
        functionAuthor: '',
        columns: []
      },
      //操作标识
      operation: '',
      //默认弹出框状态
      addTableInfoStatus: false,
      tableInfo: [],
      tableInfoOne: {
        columnId: 0,
        tableId: 0,
        operation: '',
        tableName: '',
        columnComment: '',
        columnName: '',
        columnType: '',
        oldColumnName: '',
        len: 0
      },

      rules: {
        columnComment: [{ required: true, message: '请选择名称', trigger: 'blur' }],
        columnName: [
          { required: true, message: '请输入表字段', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        columnType: [{ required: true, message: '请选择类型', trigger: 'blur' }],
        len: [{ required: true, message: '请输入长度', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.operation = this.$route.query && this.$route.query.operation
    this.info.columns.push(
      { columnComment: '主键', columnName: 'id', columnType: 'int', len: 64 },
      { columnComment: '创建人', columnName: 'create_by', columnType: 'varchar', len: 64 },
      { columnComment: '创建时间', columnName: 'create_time', columnType: 'datetime', len: 0 },
      { columnComment: '更新人', columnName: 'update_by', columnType: 'varchar', len: 64 },
      { columnComment: '更新时间', columnName: 'update_time', columnType: 'datetime', len: 0 },
      { columnComment: '删除标志', columnName: 'del_flag', columnType: 'char', len: 1 }
    )
  },
  methods: {
    //删除数据
    deleteTableInfo(row) {
      const $this = this
      let index1 = 0
      this.$modal
        .confirm('是否确认删除表字段名为？')
        .then(function () {
          $this.info.columns.map(function (item) {
            if (row.columnName == item.columnName) {
              $this.info.columns.pop(index1)
              return
            }
            index1++
          })
        })
        .then(() => {
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    //明细
    details(row) {
      this.tableInfoOne.operation = 'details'
      this.disable = true
      this.tableInfoOne.columnComment = row.columnComment
      this.tableInfoOne.columnName = row.columnName
      this.tableInfoOne.columnType = row.columnType
      this.tableInfoOne.len = row.len
      this.addTableInfoStatus = true
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.tableInfo = []
      selection.map((item) =>
        this.tableInfo.push({
          len: item.len,
          columnType: item.columnType,
          columnName: item.columnName,
          columnComment: item.columnComment,
          oldColumnName: item.columnName,
          columnId: item.columnId
        })
      )
    },

    //修改操作
    editTableInfo(row) {
      if (!row.columnName) {
        this.tableInfoOne.columnComment = this.tableInfo[0].columnComment
        this.tableInfoOne.columnName = this.tableInfo[0].columnName
        this.tableInfoOne.columnType = this.tableInfo[0].columnType
        this.tableInfoOne.len = this.tableInfo[0].len
      } else {
        this.tableInfoOne.columnComment = row.columnComment
        this.tableInfoOne.columnName = row.columnName
        this.tableInfoOne.columnType = row.columnType
        this.tableInfoOne.len = row.len
      }

      this.tableInfoOne.operation = 'change'
      this.disable = false
      this.addTableInfoStatus = true
    },

    //确定修改-添加字段按钮
    submitFromInfoOne(op) {
      if (op == 'add') {
        this.info.columns.push(this.tableInfoOne)
        this.tableInfoOne = {
          columnId: 0,
          tableId: 0,
          operation: '',
          tableName: '',
          columnComment: '',
          columnName: '',
          columnType: '',
          oldColumnName: '',
          len: 0
        }
        this.addTableInfoStatus = false
      } else if (op == 'change') {
        const sign = this.tableInfoOne
        this.info.columns.map(function (item) {
          if (sign.columnName == item.columnName) {
            item.columnComment = sign.columnComment
            item.columnName = sign.columnName
            item.columnType = sign.columnType
            item.len = sign.len
            return
          }
        })
        this.addTableInfoStatus = false
        this.tableInfoOne = {
          columnId: 0,
          tableId: 0,
          operation: '',
          tableName: '',
          columnComment: '',
          columnName: '',
          columnType: '',
          oldColumnName: '',
          len: 0
        }
      }
    },
    //添加数据库表的字段
    addTableInfo() {
      this.tableInfoOne.operation = 'add'
      this.disable = false
      this.addTableInfoStatus = true
    },

    //页面刷新
    refresh() {
      this.activeName = 'basic'
    },

    mouseleave(data) {
      data.show = false
    },

    mouseenter(data) {
      data.show = true
    },

    /** 提交按钮 */
    submitForm() {
      const datatable = Object.assign({})
      datatable.columns = Object.assign(this.info.columns)
      datatable.tableName = this.info.tableName
      datatable.tableComment = this.info.tableComment
      datatable.remark = this.info.remark
      datatable.functionAuthor = this.info.functionAuthor

      if (datatable.tableName == '' || datatable.tableName == undefined || datatable.tableComment == '' || datatable.tableComment == undefined) {
        this.$message({
          message: '请填写表描述和表名称',
          type: 'warning'
        })

        return
      }
      createSql(datatable).then((res) => {
        this.$modal.msgSuccess(res.msg)
        if (res.code === 200) {
          this.$router.push({ path: '/data/business' })
        }
      })
    },

    getFormPromise(form) {
      return new Promise((resolve) => {
        form.validate((res) => {
          resolve(res)
        })
      })
    },
    /** 关闭按钮 */
    close() {
      const obj = { path: '/data/business', query: { t: Date.now(), pageNum: this.$route.query.pageNum } }
      this.$tab.closeOpenPage(obj)
    }
  },
  mounted() {
    const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
    const sortable = Sortable.create(el, {
      handle: '.allowDrag',
      onEnd: (evt) => {
        const targetRow = this.info.columns.splice(evt.oldIndex, 1)[0]
        this.info.columns.splice(evt.newIndex, 0, targetRow)
        for (let index in this.info.columns) {
          this.info.columns[index].sort = parseInt(index) + 1
        }
      }
    })
  }
}
</script>

<style lang="scss" scoped>
.el-card {
  min-width: 200px;
  margin-right: 10px;
}
.card-box {
  padding: 0px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.hi-op {
  margin: 10px;
  align-items: center;
  justify-content: space-between;
}
</style>
